<template>
  <div>
    <!--  面包屑导航   -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!--        卡片  -->
    <el-card class="box-card">
      <!--          添加分类button  -->
      <el-button type="primary" @click="addCate">添加分类</el-button>
      <!--  分类列表  -->
      <tree-table show-index index-text="#" border :data="cateList" :columns="columns" :selection-type="false"
                  :expand-type="false" style="margin-top: 15px">
        <!--  使用作用域插槽渲染是否有效列 -->
        <template slot="isSuccess" slot-scope="scope">
          <i style="color: red" v-if="scope.row.cat_deleted === false" class="el-icon-circle-close"></i>
          <i v-else style="color: green" class="el-icon-circle-check"></i>
        </template>
        <!--  使用作用域插槽渲染排序列 -->
        <template slot="sort" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag size="mini" v-else type="warning">三级</el-tag>
        </template>
        <!--  使用作用域插槽渲染操作列 -->
        <template slot="opt" slot-scope="scope">
          <el-button size="mini" @click="alterBtn(scope.row)" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteBtn(scope.row.cat_id)" icon="el-icon-delete">删除</el-button>
        </template>
      </tree-table>
      <!--  分页  -->
      <el-pagination :page-sizes="[2, 5, 10, 15]" :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="this.total" @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"></el-pagination>
    </el-card>
    <!--  添加分类的对话框  -->
    <el-dialog @close="addClose" style="text-align: left" title="添加分类" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name" type="text"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="cat_name">
          <!--  级联选择添加父级分类  -->
          <el-cascader v-model="selectedCate" clearable :options="parentsOptions"
                       :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children' ,checkStrictly:true}"
                       @change="addCascaderChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!--  编辑商品分类的对话框  -->
    <el-dialog :visible.sync="alterDialogVisible" title="编辑分类">
      <el-form :model="alterForm" :rules="addFormRules" ref="alterFormRef" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="alterForm.cat_name" type="text"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="alterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="alterSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Cate",
    data() {
      return {
        alterDialogVisible: false,
        alterForm: {
          cat_name: ''
        },

        /*  存放选中的父级id */
        selectedCate: [],
        parentsOptions: [],
        addDialogVisible: false,
        addForm: {
          cat_name: '',
          /*  父级分类的id */
          cat_pid: 0,
          /*  分类等级，默认一级*/
          cat_level: 0,
        },
        addFormRules: {
          cat_name: [
            {
              required: true, message: '请输入分类名称', trigger: 'blur'
            }
          ]
        },
        /*  表格各列的配置 */
        columns: [
          {
            label: '分类名称',
            prop: 'cat_name',
          },
          {
            label: '是否有效',
            type: 'template',
            template: 'isSuccess',
          },
          {
            label: '排序',
            type: 'template',
            template: 'sort',
          },
          {
            label: '操作',
            type: 'template',
            template: 'opt'
          }
        ],
        /*  查询条件 ,参数对象 */
        queryInfo: {
          type: 3,
          pagenum: 1,
          pagesize: 5
        },
        cateList: [],
        total: 0
      }
    },
    created() {
      this.getCateList();
    },

    methods: {
      /*  删除该分类 */
      deleteBtn(deleteId) {
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          /*  确定删除该用户 */
          const {data: deleteRes} = await this.$http.delete("categories/" + deleteId);
          if (deleteRes.meta.status === 200) {
            this.$message.success("成功删除用户");
            this.getCateList();
          } else {
            this.$message.error("删除用户失败");
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      /*  确定提交编辑  */
      alterSubmit() {
        this.$refs.alterFormRef.validate(async (valid) => {
          if (!valid) {
            this.$message.error('请输入分类名称');
          } else {
            const {data: alterRes} = await this.$http.put('categories/' + this.alterForm.cat_id, {cat_name: this.alterForm.cat_name})
            if (alterRes.meta.status === 200){
              this.getCateList();
              this.alterDialogVisible = false;
              this.$message.success('编辑提交成功');
            }else {
              this.$message.error('编辑提交失败');
            }
          }
        })
      },
      /*  编辑分类名称  */
      alterBtn(scopeData) {
        this.alterForm = scopeData;
        this.alterDialogVisible = true;
      },
      /*  确定添加分类  */
      addSubmit() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) {
            this.$message.error('请输入分类名称')
          } else {
            const {data: subRes} = await this.$http.post('categories', this.addForm);
            if (subRes.meta.status === 201) {
              this.$message.success('提交成功');
              this.addDialogVisible = false;
              this.getCateList();
            } else {
              this.$message.error('提交失败');
            }
          }
        })
      },
      /*  监听对话框关闭 ，重置表单数据  */
      addClose() {
        this.$refs.addFormRef.resetFields();
        this.addForm.cat_pid = 0;
        this.addForm.cat_level = 0;
        this.selectedCate = []
      },
      /*  监听选择父级分类发生变化  */
      addCascaderChange() {
        if (this.selectedCate.length > 0) {
          this.addForm.cat_pid = this.selectedCate[this.selectedCate.length - 1];
          this.addForm.cat_level = this.selectedCate.length;
        } else {
          this.addForm.cat_level = 0;
          this.addForm.cat_pid = 0;
        }
        /*   console.log(this.addForm);*/
      },
      /* 获取父级分类的列表数据 */
      async getParentsOptionsList() {
        const {data: parentRes} = await this.$http.get('categories', {params: {type: 2}});
        if (parentRes.meta.status === 200) {
          this.parentsOptions = parentRes.data;
        } else {
          this.$message.error('获取父级分类数据失败');
        }
      },
      /*  添加分类  */
      addCate() {
        this.getParentsOptionsList();
        this.addDialogVisible = true;
      },
      /*  当前页*/
      handleCurrentChange(currentPage) {
        this.queryInfo.pagenum = currentPage;
        this.getCateList();
      },
      /*  每页条数  */
      handleSizeChange(val) {
        this.queryInfo.pagesize = val;
        this.getCateList();
      },
      /*  获取商品分类列表数据  */
      async getCateList() {
        const {data: res} = await this.$http.get('categories', {params: this.queryInfo});
        // console.log(res.data);
        if (res.meta.status === 200) {
          this.cateList = res.data.result;
          this.total = res.data.total;
        } else {
          this.$message.error('获取商品分类数据失败');
        }
      }
    }
  }
</script>

<style scoped>
  .el-cascader {
    width: 100%;
  }
</style>
